<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 获取POST数据
$action = $_POST['action'] ?? '';
$orderId = intval($_POST['order_id'] ?? 0);
$settlementType = $_POST['settlement_type'] ?? 'principal';
$settlementAmount = isset($_POST['settlement_amount']) && !empty($_POST['settlement_amount']) ? floatval($_POST['settlement_amount']) : null;
$settlementInfo = $_POST['settlement_info'] ?? '批量结算操作';

error_log("批量结算处理 - 订单ID: {$orderId}, 结算类型: {$settlementType}, 结算金额: " . ($settlementAmount ?? '空'));

if ($action !== 'settle_single' || $orderId <= 0) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

$db = getDB();

try {
    // 获取订单信息
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    
    if (!$order) {
        throw new Exception("订单不存在");
    }
    
    // 开始事务
    $db->beginTransaction();
    
    // 使用与 batch_operations.php 相同的结算逻辑
    $operationType = ($settlementType == 'commission') ? 'settle_principal' : 'settle_commission';
    $dbSettlementType = ($settlementType == 'commission') ? 'principal' : 'principal_commission';
    
    error_log("操作类型: {$operationType}, 数据库结算类型: {$dbSettlementType}");
    
    // 计算结算金额
    $finalAmount = $settlementAmount;
    if ($finalAmount !== null && $finalAmount > 0) {
        // 使用传入的金额
        $finalAmount = $settlementAmount;
    } else {
        // 自动计算金额 - 与 batch_operations.php 保持一致
        if ($settlementType == 'commission') {
            $finalAmount = $order['order_amount']; // 结本金：只结本金
        } else {
            $finalAmount = $order['order_amount'] * 1; // 结本金+佣金：本金+10%佣金
        }
    }
    
    error_log("最终结算金额: {$finalAmount}");
    
    // 更新订单 - 使用与 batch_operations.php 相同的更新逻辑
    $updateSql = "UPDATE orders SET 
        is_registered = 1, 
        status = 'settled', 
        settlement_type = ?, 
        settlement_amount = ?, 
        settlement_info = ?, 
        admin_id = ?, 
        updated_at = NOW() 
        WHERE id = ?";
    
    error_log("更新SQL: {$updateSql}");
    error_log("参数: {$dbSettlementType}, {$finalAmount}, {$settlementInfo}, {$_SESSION['user_id']}, {$orderId}");
    
    $stmt = $db->prepare($updateSql);
    if (!$stmt->execute([$dbSettlementType, $finalAmount, $settlementInfo, $_SESSION['user_id'], $orderId])) {
        $errorInfo = $stmt->errorInfo();
        error_log("订单更新错误详情: " . print_r($errorInfo, true));
        throw new Exception("订单更新失败: " . ($errorInfo[2] ?? '未知错误'));
    }
    
    // 记录操作 - 使用与 batch_operations.php 相同的记录逻辑
    if (!recordOrderOperation($orderId, $operationType, $finalAmount, $settlementInfo, [], $_SESSION['user_id'])) {
        throw new Exception("操作记录失败");
    }
    
    // 处理结算记录 - 使用与 batch_operations.php 相同的处理逻辑
    if (!processOrderSettlementNew($orderId, $settlementType, $finalAmount, $settlementInfo, [], $_SESSION['user_id'])) {
        throw new Exception("结算记录处理失败");
    }
    
    // 提交事务
    $db->commit();
    
    error_log("订单 {$orderId} 结算成功");
    
    echo json_encode([
        'success' => true,
        'message' => "结算成功，金额：" . formatAmount($finalAmount),
        'amount' => $finalAmount
    ]);
    
} catch (Exception $e) {
    // 回滚事务
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    error_log("订单 {$orderId} 结算失败: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>